#include "instrument.h"
#include <QtWidgets>

instrument::instrument(QWidget *parent) : QWidget(parent)
{
   Image_name= QString("");
   ins_num=QString("");
   this->installEventFilter(this);
}



void instrument::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    /*图片区*/

    QImage image(Image_name);
    painter.drawImage(0,0, image);
    /*文字区*/
    QRectF rect(35.0, 25.0, 40.0, 30.0);
    QFont font;
    font.setBold(true);
    painter.setFont(font);
    painter.setPen(Qt::black);
    painter.drawText(rect, Qt::AlignCenter, ins_num);
}



void instrument::set_string(QString num)
{
    ins_num = num;
}



void instrument::set_Image(const Instrument_type &instrument_type)
{

    if(instrument_type==PM_monitor)
        Image_name= QString(":/new/prefix1/image/PM_monitor .png");
    if(instrument_type==HCHO_monitor)
        Image_name= QString(":/new/prefix1/image/HCHO_monitor.png");
    if(instrument_type==humiture_monitor)
        Image_name= QString(":/new/prefix1/image/humiture_monitor.png");
    if(instrument_type==air_monitoring_station)
        Image_name= QString(":/new/prefix1/image/air_monitoring_station.png");
    if(instrument_type==air_cleaner)
        Image_name= QString(":/new/prefix1/image/air_cleaner.png");
    if(instrument_type==visual_presentation)
        Image_name= QString(":/new/prefix1/image/visual_presentation.png");
        update();
}


bool instrument::eventFilter(QObject *watched, QEvent *event)
{
        static QPoint lastPoint;
        static bool isPressed = false;

        if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent *e = static_cast<QMouseEvent *>(event);
            if (this->rect().contains(e->pos()) && (e->button() == Qt::LeftButton)) {
                lastPoint = e->pos();
                isPressed = true;
            }
        }
        else if (event->type() == QEvent::MouseMove && isPressed) {
            QMouseEvent *e = static_cast<QMouseEvent *>(event);
            int dx = e->pos().x() - lastPoint.x();
            int dy = e->pos().y() - lastPoint.y();
            this->move(this->x() + dx, this->y() + dy);
            return true;
        }
        else if (event->type() == QEvent::MouseButtonRelease && isPressed) {
            isPressed = false;
        }
    return QWidget::eventFilter(watched, event);
}
